package com.gbdata.zuul.filter;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UrlPathHelper;

@Component
public class ReloadRequestFilter extends ZuulFilter {
    private UrlPathHelper urlPathHelper = new UrlPathHelper();
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    @Qualifier("eurekaClient")
    private EurekaClient eurekaClient;
    @Autowired
    private ProxyRequestHelper helper;

    public ReloadRequestFilter() {
    }

    @Override
    public String filterType() {
        return "route";
    }

    @Override
    public int filterOrder() {
        return 99;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String requestURL = ctx.getRequest().getRequestURL().toString();
        return requestURL.contains("dict/") && requestURL.contains("reload");
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String)ctx.get("serviceId");
        List<InstanceInfo> instances = this.eurekaClient.getApplication(serviceId).getInstances();
        String uri = this.helper.buildZuulRequestURI(ctx.getRequest());
        uri = uri.replace("//", "/");
        Iterator var5 = instances.iterator();

        while(var5.hasNext()) {
            InstanceInfo instance = (InstanceInfo)var5.next();
            String homePageUrl = instance.getHomePageUrl();
            if (homePageUrl.charAt(homePageUrl.length() - 1) == '/') {
                homePageUrl = homePageUrl.substring(0, homePageUrl.length() - 1);
            }

            String url = homePageUrl + uri;

            try {
                for(int i = 0; i < 3; ++i) {
                    Integer statusCode = (Integer)this.restTemplate.execute(new URI(url), HttpMethod.POST, (request) -> {
                    }, (response) -> {
                        return response.getStatusCode().value();
                    });
                    if (statusCode != null && statusCode == 200) {
                        break;
                    }
                }
            } catch (URISyntaxException var11) {
                var11.printStackTrace();
            }
        }

        return null;
    }
}
